package com.bnyy.medicalHousekeeper.moudle.message.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.Article;
import com.bnyy.medicalHousekeeper.bean.Customer;
import com.bnyy.medicalHousekeeper.bean.Shop;
import com.bnyy.medicalHousekeeper.bean.Subordinate;
import com.bnyy.medicalHousekeeper.moudle.message.MessageManager;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.ContactAdapter;
import com.bnyy.medicalHousekeeper.moudle.message.adapter.Share2ContactAdapter;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bnyy.message.bean.Contact;
import com.bnyy.message.bean.ContactGroup;
import com.bnyy.message.bean.ContactUser;
import com.bnyy.message.bean.chat.ChatMessage;
import com.bnyy.message.bean.chat.message_data.ArticleMessage;
import com.bnyy.message.bean.chat.message_data.MessageData;
import com.bnyy.message.enums.MessageType;
import com.bnyy.message.event.SendMessageEvent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.function.Function;
import java.util.stream.Collectors;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/11/10
 **/
public class Share2ContactsActivity extends BaseActivityImpl {
    @BindView(R.id.ll_search)
    RelativeLayout llSearch;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.recycler_view_selected_contacts)
    RecyclerView recyclerViewSelectedContacts;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.ll_selected_contacts)
    LinearLayout llSelectedContacts;

    private ArrayList<Contact> selectedContacts = new ArrayList<>();
    private Share2ContactAdapter selectedContactAdapter;
    private ContactAdapter contactAdapter;

    private ContactAdapter.CallbackImpl callback = new ContactAdapter.CallbackImpl() {
        @Override
        public void onConstantItemClick(ContactAdapter.Constant constant) {
            super.onConstantItemClick(constant);
            showConstantPopWin(constant);
        }

        @Override
        public void onCheck(Contact contact, boolean checked, int position) {
            super.onCheck(contact, checked, position);
            if (checked) {
                if (llSelectedContacts.getVisibility() != View.VISIBLE) {
                    llSelectedContacts.setVisibility(View.VISIBLE);
                }
                selectedContacts.add(contact);
                selectedContactAdapter.loadMore(contact);
            } else {
                if (contact instanceof ContactGroup) {
                    for (int i = 0; i < selectedContacts.size(); i++) {
                        Contact c = selectedContacts.get(i);
                        if (c instanceof ContactGroup) {
                            if (c.getId() == contact.getId()) {
                                selectedContactAdapter.remove(i);
                                break;
                            }
                        }
                    }
                } else {
                    for (int i = 0; i < selectedContacts.size(); i++) {
                        if (selectedContacts.get(i).getId() == contact.getId()) {
                            selectedContacts.remove(i);
                            selectedContactAdapter.remove(i);
                            break;
                        }
                    }
                }
                if (selectedContacts.size() == 0) {
                    llSelectedContacts.setVisibility(View.GONE);
                }
            }
        }
    };

    public static void show(Context context, MessageData messageData) {
        Intent intent = new Intent(context, Share2ContactsActivity.class);
        intent.putExtra("messageData", messageData);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_message_share_2_contacts;
    }

    @Override
    public String getTitleStr() {
        return "分享至";
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SendMessageEvent event) {
        switch (event.getMessageType()) {
            case USER_HOMEPAGE:
            case GROUP_CHAT_INVITATION:
                finish();
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recyclerViewSelectedContacts.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        selectedContactAdapter = new Share2ContactAdapter(mContext);
        recyclerViewSelectedContacts.setAdapter(selectedContactAdapter);

        HashMap<String, Object> params = new HashMap<>();
        params.put("page_index", 1);
        params.put("page_size", 1000);
        params.put("tag_type", 7);
        requestManager.request(requestManager.mJavaRetrofitService.getCustomerList(RequestManager.getJsonRequestBody(params)),
                new BaseObserverImpl<ArrayList<Customer>>(mContext) {
                    @Override
                    public void onSuccess(ArrayList<Customer> customers) {
                        super.onSuccess(customers);
                        contactAdapter.refresh(new ArrayList<>(customers.stream()
                                        .map(new Function<Customer, ContactUser>() {
                                            @Override
                                            public ContactUser apply(Customer customer) {
                                                ContactUser contactUser = new Customer();
                                                contactUser.setUser_img(customer.getUser_image());
                                                contactUser.setUsername(customer.getUser_name());
                                                contactUser.setRole_id(customer.getRole_id());
                                                contactUser.setId(customer.getId());
                                                return contactUser;
                                            }
                                        })
                                        .collect(Collectors.toList())),
                                new ContactAdapter.ConstantItem("全部用户", ContactAdapter.Constant.GROUP));
                    }
                });

//        requestManager.request(requestManager.mMessageRetrofitService.getFriendList(),
//                new BaseObserverImpl<ArrayList<ContactUser>>(mContext) {
//                    @Override
//                    public void onSuccess(ArrayList<ContactUser> contactUsers) {
//                        super.onSuccess(contactUsers);
//                        contactAdapter.refresh(contactUsers,
//                                new ContactAdapter.ConstantItem("全部关注", ContactAdapter.Constant.GROUP));
//                    }
//                });

        contactAdapter = new ContactAdapter(mContext, false, callback);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(contactAdapter);

        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageData messageData = (MessageData) getIntent().getSerializableExtra("messageData");

                if (messageData.getMessageType() == MessageType.ARTICLE) {
                    ArticleMessage articleMessage = (ArticleMessage) messageData;
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("id", articleMessage.getId());
                    params.put("frequency", selectedContacts.size());

                    requestManager.request(requestManager.mJavaRetrofitService.saveShareRecord(RequestManager.getJsonRequestBody(params)),
                            new BaseObserverImpl<Article>(mContext) {
                                @Override
                                public void onSuccess(Article article) {
                                    super.onSuccess(article);
                                    articleMessage.setShareId(article.getShareId());
                                    share(articleMessage);
                                }
                            });
                } else {
                    share(messageData);
                }
            }
        });
    }

    private void share(MessageData messageData) {
        for (Contact contact : selectedContacts) {
            ChatMessage chatMessage = new ChatMessage(contact, userInfoManager.getLoginUserInfo(), messageData.getMessageType());
            chatMessage.setMessageData(messageData);
            messageData.setMsgId(chatMessage.getMsgId());
            MessageManager.sendChatMessage(chatMessage);
        }
        Toast.makeText(mContext, "分享成功", Toast.LENGTH_SHORT).show();
        finish();
    }

    private void showConstantPopWin(ContactAdapter.Constant constant) {
        ContactAdapter.ConstantItem constantItem = new ContactAdapter.ConstantItem(constant.getName());
        HashSet<Integer> set = new HashSet<>();
        for (Contact contact : selectedContacts) {
            set.add(contact.getId());
        }
        switch (constant) {
            case GROUP:
                requestManager.request(requestManager.mMessageRetrofitService.getGroupList(),
                        new BaseObserverImpl<ArrayList<ContactGroup>>() {
                            @Override
                            public void onSuccess(ArrayList<ContactGroup> contactGroups) {
                                super.onSuccess(contactGroups);
                                if (contactGroups.size() > 0) {
                                    SelectContactActivity.showMultipleSelectConstantPopWin(mContext, contactGroups, constant, set, callback);
                                } else {
                                    Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                break;
            case FAMILY:
                requestManager.request(requestManager.mMessageRetrofitService.getFamilyList(),
                        new BaseObserverImpl<ArrayList<ContactUser>>() {
                            @Override
                            public void onSuccess(ArrayList<ContactUser> contactUsers) {
                                super.onSuccess(contactUsers);
                                if (contactUsers.size() > 0) {
                                    SelectContactActivity.showMultipleSelectConstantPopWin(mContext, contactUsers, constant, set, callback);
                                } else {
                                    Toast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                break;
        }
    }
}



















